package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.BusinessException;
import com.demo.core.exception.ParameterException;
import com.demo.dao.LikeDao;
import com.demo.domain.Comment;
import com.demo.domain.Like;
import com.demo.domain.Post;
import com.demo.domain.Reply;
import com.demo.domain.ro.*;
import com.demo.domain.vo.CommentView;
import com.demo.domain.vo.ReplyView;
import com.demo.service.*;
import com.demo.websocket.WebSocketServer;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private LikeService likeService;

    /**
     * 根据条件获取帖子
     *
     * @param pageRequest
     * @param sortBy
     * @param searchKeyword
     * @return
     * @throws ParameterException
     */
    @PostMapping(value = "/postDisplay")
    public Result getPostByCommentCount(@RequestBody PageRequest pageRequest,
                                        @RequestParam(name = "sortBy", required = false, defaultValue = "release_time") String sortBy,
                                        @RequestParam(name = "searchKeyword", required = false) String searchKeyword,
                                        @RequestParam(name="type",required = false, defaultValue = "0")int type
    ) {
        try {
            return postService.getPostByCommentCount(pageRequest, sortBy, searchKeyword, type);
        } catch (ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * 详细的帖子内容
     * @param postId
     * @return
     * @throws ParameterException
     */
    @GetMapping(value="/postContent/{postId}")
    public Result getPostContent(@PathVariable Long postId) throws ParameterException{
        if(postId == null || postId <= 0L){
            throw new ParameterException("postId为空或非法");
        }
        Post post = postService.getPostById(postId);
        if(post == null){
            return Result.success(HttpStatus.NO_CONTENT, "帖子不存在",null);
        }
        return Result.success(HttpStatus.SUCCESS, "获取帖子内容成功", post);
    }

    /**
     * 帖子对应的评论接口
     * @param postId
     * @param currentPage
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @GetMapping(value = "/postComments/{postId}/{currentPage}")
    public Result getPostCommentsWithReplies(@PathVariable Long postId, @PathVariable int currentPage, HttpServletRequest request) throws ParameterException {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        try {
            return commentService.getPostCommentsWithReplies(postId, currentPage,uid);
        } catch (ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * 提交评论
     *
     * @param saveCmtRequest
     * @return
     * @throws IOException
     * @throws ParameterException
     */
    @AuthorizationRequired
    @PostMapping(value = "/saveComment")
    public Result saveComment(@RequestBody SaveCmtRequest saveCmtRequest,HttpServletRequest request) {
        try {
            Long uid = (Long) request.getAttribute("userId");
            return commentService.saveComment(saveCmtRequest,uid);
        } catch (IOException | ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * 每条评论对应的回复接口
     * @param commentId
     * @param currentPage
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @GetMapping(value = "/postReplies/{commentId}/{currentPage}")
    public Result getCommentReplies(@PathVariable Long commentId, @PathVariable int currentPage,HttpServletRequest request) throws ParameterException {
        if (commentId == null || commentId <= 0L) {
            throw new ParameterException("commentId为空或非法");
        }
        if (currentPage <= 0) {
            throw new ParameterException("currentPage值非法");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        Reply reply = new Reply();
        reply.setCid(commentId);
        List<ReplyView> replyList = replyService.getReplyWithoutPage(currentPage, reply,uid);
        return Result.success(HttpStatus.SUCCESS, "获取回复成功", replyList);
    }

    /**
     * 提交回复
     *
     * @param saveReRequest
     * @return
     * @throws IOException
     * @throws ParameterException
     */
    @AuthorizationRequired
    @PostMapping(value = "/saveReply")
    public Result saveReply(@RequestBody SaveReRequest saveReRequest,HttpServletRequest request) throws IOException, ParameterException {
        try {
            Long uid = (Long) request.getAttribute("userId");
            return replyService.saveReply(saveReRequest, uid);
        } catch (IOException | ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * 提交帖子
     *
     * @param savePostRequest
     * @return
     * @throws IOException
     * @throws ParameterException
     */
//    v-model绑定 value-类型
    @AuthorizationRequired
    @PostMapping(value = "/savePost")
    public Result savePost(@RequestParam(value = "file", required = false) MultipartFile[] imageFiles, SavePostRequest savePostRequest,HttpServletRequest request) throws IOException, ParameterException {
        try {
            Long uid = (Long) request.getAttribute("userId");
            return postService.savePost(imageFiles, savePostRequest,uid);
        } catch (IOException | ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * 点赞
     *
     * @param likeRequest
     * @return
     * @throws IOException
     */
    @AuthorizationRequired
    @PostMapping("/like")
    public Result like(@RequestBody LikeRequest likeRequest,HttpServletRequest request) throws ParameterException {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        try {
            return likeService.like(likeRequest,uid);
        } catch (IOException | ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    /**
     * 获取文件的URL
     *
     * @param file
     * @return
     */
    @PostMapping("/file")
    public String getFileUrl(@RequestParam(name = "file") MultipartFile file) throws ParameterException {
        if (file == null) {
            throw new ParameterException("file为null");
        }
//        获取上传的文件的原始文件名
        String fileName = file.getOriginalFilename();
//        将文件名编码为URL安全的格式,并和基本的图片URL地址拼接在一起
        String imageUrl = "http://8.130.133.61:8081/images/" + URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        return imageUrl;
    }
}
